<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-left">
        <el-input size="mini" v-model="searchKey" placeholder="订单名称/编号/详情/备注/创建人" style="width: 250px"
          class="filter-item" @keyup.enter.native="handleFilter" @input="handleFilter" />
        <!-- <el-button
          size="mini"
          v-waves
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >
          查询
        </el-button> -->
      </div>
      <div class="filter-right">
        <el-button icon="el-icon-plus" type="primary" size="mini" @click="handleAdd">
          新增订单
        </el-button>
        <el-button icon="el-icon-upload2" type="primary" size="mini" @click="uploadFiles">
          氚云导入
        </el-button>
      </div>
    </div>
    <el-table :data="pageList" border stripe fit highlight-current-row v-loading="listLoading" style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="order_name" label="订单名称" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="order_id" label="氚云订单号" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="order_details" label="订单详情" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="brand_name" label="品牌名称" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="创建方式" align="center" width="120">
        <template slot-scope="{ row }">
          <el-tag v-if="row.chuanyun_object_id" key="氚云导入">氚云导入</el-tag>
          <el-tag v-else key="OA创建" type="warning">OA创建</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="chuanyun_pm_name" label="氚云PM" align="center" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column prop="create_username" label="创建人" align="center">
        <template slot-scope="{ row }">
          {{ row.chuanyun_object_id ? row.chuanyun_pm_name : row.create_username }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.created_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="200px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.updated_at | formate }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button @click="handleDetails(scope.row)" type="text" size="small" style="color: green">查看详情</el-button>
          <el-button @click="handleModify(scope.row)" type="text" size="small">修改</el-button>
          <el-button @click="handleDelete(scope.row)" type="text" size="small" style="color: red">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getPageList" />

    <!-- 新增表单 -->
    <el-dialog title="新增订单" :visible.sync="dialogFormVisible" width="550px">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="订单名称" label-width="120px" prop="orderName">
          <el-input v-model="form.orderName" autocomplete="off" maxlength="50" placeholder="请输入订单名称"
            @input="changeValue('orderName', '50')"></el-input>
        </el-form-item>
        <el-form-item label="氚云订单号" label-width="120px">
          <el-input v-model="form.orderId" autocomplete="off" maxlength="200" placeholder="请输入氚云订单号"
            oninput="value=value.replace(/[\W]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="订单详情" label-width="120px">
          <el-input v-model="form.orderDetails" autocomplete="off" maxlength="200" placeholder="请输入订单详情"
            @input="changeValue('orderDetails', '200')"></el-input>
        </el-form-item>
        <el-form-item label="归属品牌" label-width="120px">
          <el-select v-model="form.brandName" filterable clearable placeholder="请选择归属品牌" style="width: 100%">
            <el-option v-for="item in brandList" :key="item.id" :label="item.brand_name" :value="item.brand_name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="自动创建项目" label-width="120px" prop="createdProject">
          <el-radio-group v-model="form.createdProject">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" label-width="120px">
          <el-input type="textarea" rows="5" resize="none" maxlength="200" @input="changeValue('remarks', '200')"
            placeholder="请输入内容" v-model="form.remarks">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改表单 -->
    <el-dialog title="修改订单" :visible.sync="modifyFormVisible" width="550px">
      <el-form :model="modifyForm" :rules="modifyRules" ref="modifyForm">
        <el-form-item label="订单名称" label-width="100px" prop="orderName">
          <el-input v-model="modifyForm.orderName" :disabled="!!modifyForm.chuanyun_object_id" autocomplete="off"
            maxlength="50" @input="changeValueModify('orderName', '50')"></el-input>
        </el-form-item>
        <el-form-item label="氚云订单号" label-width="100px">
          <el-input v-model="modifyForm.orderId" :disabled="!!modifyForm.chuanyun_object_id" autocomplete="off"
            maxlength="200" oninput="value=value.replace(/[\W]/g,'')"></el-input>
        </el-form-item>
        <el-form-item label="订单详情" label-width="100px">
          <el-input v-model="modifyForm.orderDetails" autocomplete="off" maxlength="200"
            @input="changeValueModify('orderDetails', '200')"></el-input>
        </el-form-item>
        <el-form-item label="归属品牌" label-width="100px">
          <el-select v-model="modifyForm.brandName" filterable clearable placeholder="请选择归属品牌" style="width: 100%">
            <el-option v-for="item in brandList" :key="item.id" :label="item.brand_name" :value="item.brand_name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input type="textarea" rows="5" resize="none" maxlength="200" @input="changeValueModify('remarks', '200')"
            placeholder="请输入内容" v-model="modifyForm.remarks">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyForms('modifyForm')">取 消</el-button>
        <el-button type="primary" @click="submitModify('modifyForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 氚云订单导入 -->
    <el-dialog title="氚云导入订单" :visible.sync="mergeUploadDialogVisible" :destroy-on-close="true" width="400px">
      <div v-loading="chuanyunUploadDialogLoading">
        <div style="margin-bottom: 20px;">
          <el-upload ref="uploadFile" class="uploadTool" drag action="" :file-list="uploadFileList" accept=".xlsx,.xls"
            :auto-upload="false" :on-change="uploadChange">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              只能上传excel文件
            </div>
          </el-upload>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirUpload" size="medium">确定</el-button>
          <el-button type="info" @click="mergeUploadDialogVisible = false" size="medium ">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getOrderPage,
  createdOrder,
  getProjLists,
  updateOrderInfo,
  delOrderInfo,
  uploadOrdersFile,
  uploadChuanyunOrdersFile
} from "@/api/order";
import { checkUserToken } from "@/api/user";
import { getAllBrandsPage } from "@/api/brand";
import waves from "@/directive/waves"; // waves directive
import { curentTime } from "@/filters/index";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
export default {
  name: "Order",
  components: { Pagination },
  directives: { waves },
  filters: {
    formate(date) {
      return curentTime(date);
    },
  },
  data() {
    return {
      // 订单数据
      pageList: [],
      // 订单总数
      total: 0,
      // 加载
      listLoading: true,
      // 查询条件
      listQuery: {
        pageNum: 1,
        pageSize: 10,
      },
      searchKey: "",
      // 表单控制
      dialogFormVisible: false,
      modifyFormVisible: false,
      mergeUploadDialogVisible: false,
      chuanyunUploadDialogLoading: false,
      // 新增表单信息
      form: {
        brandName: "",
        orderName: "",
        orderId: "",
        orderDetails: "",
        createdProject: "0",
        remarks: "",
      },
      // 修改表单信息
      modifyForm: {
        id: "",
        brandName: "",
        orderName: "",
        orderId: "",
        orderDetails: "",
        remarks: "",
      },
      // 项目ID
      projectId: "",
      // 修改订单ID
      orderId: "",
      // 表单校验
      rules: {
        orderName: [
          { required: true, message: "请输入订单名称", trigger: "blur" },
        ],
        // orderDetails: [
        //   { required: true, message: "请输入订单详情", trigger: "blur" },
        // ],
        createdProject: [
          { required: true, message: "请选择是否关联项目", trigger: "change" },
        ],
        // projectId: [
        //   { required: true, message: "请选择关联项目", trigger: "change" },
        // ],
      },
      modifyRules: {
        orderName: [
          { required: true, message: "请输入订单名称", trigger: "blur" },
        ],
        // orderDetails: [
        //   { required: true, message: "请输入订单详情", trigger: "blur" },
        // ],
      },
      // 关联项目数据
      options: [],
      // 批量上传
      uploadFileList: [],
      filedata: "",
      // 品牌信息
      brandList: [],
    };
  },
  async created() {
    await this.getPageList();
    this.getBrandDate();
  },
  methods: {
    // 按需查询
    async handleFilter() {
      this.listQuery.searchKey = this.searchKey;
      this.listQuery.pageNum = 1;
      await this.getPageList();
    },

    // 查询列表
    async getPageList() {
      try {
        const res = await getOrderPage(this.listQuery);
        this.total = res.data.total;
        this.pageList = res.data.lists;
        this.listLoading = false;
      } catch (error) {
        console.log(error);
      }
    },

    // 查询关联项目
    getProjLists() {
      getProjLists().then((res) => {
        this.options = res.data;
      });
    },

    // 新增表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          createdOrder(this.form).then((res) => {
            this.$message({
              message: "新增成功",
              type: "success",
            });
            this.getPageList();
            this.dialogFormVisible = false;
            this.resetForm("form");
          });
        } else {
          return false;
        }
      });
    },

    // 修改表单
    submitModify(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateOrderInfo(this.modifyForm).then((res) => {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getPageList();
            this.modifyFormVisible = false;
            this.modifyForms("modifyForm");
          });
        } else {
          return false;
        }
      });
    },

    // 新增订单
    handleAdd() {
      checkUserToken().then((res) => {
        if (res.data) {
          this.dialogFormVisible = true;
          this.getProjLists();
        }
      });
    },

    // 批量上传
    uploadFiles() {
      checkUserToken().then((res) => {
        if (res.data) {
          this.mergeUploadDialogVisible = true;
        }
      });
    },

    // 修改订单
    handleModify(row) {
      console.log(row, 'rowrowrowrow')
      this.modifyForm.id = row.id;
      this.modifyForm.brandName = row.brand_name;
      this.modifyForm.orderName = row.order_name;
      this.modifyForm.orderId = row.order_id;
      this.modifyForm.orderDetails = row.order_details;
      this.modifyForm.remarks = row.remarks;
      this.modifyForm.chuanyun_object_id = row.chuanyun_object_id
      this.modifyFormVisible = true;
    },

    // 订单详情
    handleDetails(row) {
      this.$router.push({ path: "/order/details", query: { id: row.id } });
    },

    // 删除订单
    handleDelete(row) {
      this.$confirm("此操作将删除该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delOrderInfo(row.id).then((res) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getPageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 取消
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
      if (this.form.remarks) {
        this.form.remarks = "";
      }
      if (this.form.orderId) {
        this.form.orderId = "";
      }
      if (this.form.brandName) {
        this.form.brandName = "";
      }

      if (this.form.orderDetails) {
        this.form.orderDetails = "";
      }
    },

    modifyForms(formName) {
      // this.$refs[formName].resetFields();
      this.modifyFormVisible = false;
    },

    uploadChange(file, files) {
      this.uploadFileList.push(file.raw);
    },
    confirUpload() {
      // 声明一个FormDate对象
      this.filedata = new FormData();
      //把文件信息放入对象中
      this.uploadFileList.map((el, index) => {
        this.filedata.append(`file${index}`, el);
      });
      this.handleUploadSuccess();
    },

    handleUploadSuccess() {
      this.chuanyunUploadDialogLoading = true;
      uploadChuanyunOrdersFile(this.filedata).then((res) => {
        if (res.success) {
          this.mergeUploadDialogVisible = false;
          this.$message.success('导入成功' + res.data.successNum + "条订单");
          this.getPageList();
          this.uploadFileList = [];
          if (res.data.errorRes && res.data.errorRes.length) {
            let idStr = "";
            res.data.errorRes.forEach((item, index) => {
              idStr += item.project_record_id + "<br/>"
            })
            this.$notify({
              type: 'warning',
              title: '导入失败数据ObjectId如下',
              dangerouslyUseHTMLString: true,
              message: idStr,
              duration: 0
            });
          }
        }
        this.chuanyunUploadDialogLoading = false;
      }).catch(e => {
        console.log("uploadChuanyunOrdersFile-err", e)
        this.chuanyunUploadDialogLoading = false;
        this.$message.error("导入失败");
      });
    },

    downloadTemplate() {
      let link = document.createElement("a"); //创建a标签
      link.style.display = "none";
      link.href =
        "https://morefun-active.oss-cn-beijing.aliyuncs.com/morefun_oa/%E8%AE%A2%E5%8D%95%E6%95%B0%E6%8D%AE%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"; //文件下载地址
      link.setAttribute("download", "订单模板"); //设置下载属性 以及文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 输入字数限制
    changeValue(attr, byte) {
      let value = this.form[attr]; //校验的字段
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let maxLimitStr = byte; //汉字个数
      let pass = true;
      let substringStr = "";
      let length = 0;
      let strArr = value.split("");
      strArr.map((str) => {
        if (pass) {
          if (cnReg.test(str)) {
            //中文
            length++;
          } else {
            //英文
            length += 0.5;
          }
          //大于最大限制的时候
          if (length > maxLimitStr) {
            pass = false;
            //将校验的字符截取返回
            this.form[attr] = substringStr;
          } else {
            substringStr += str;
          }
        }
      });
      return pass;
    },

    changeValueModify(attr, byte) {
      let value = this.modifyForm[attr]; //校验的字段
      // 中文、中文标点、全角字符按1长度，英文、英文符号、数字按0.5长度计算
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/;
      let maxLimitStr = byte; //汉字个数
      let pass = true;
      let substringStr = "";
      let length = 0;
      let strArr = value.split("");
      strArr.map((str) => {
        if (pass) {
          if (cnReg.test(str)) {
            //中文
            length++;
          } else {
            //英文
            length += 0.5;
          }
          //大于最大限制的时候
          if (length > maxLimitStr) {
            pass = false;
            //将校验的字符截取返回
            this.modifyForm[attr] = substringStr;
          } else {
            substringStr += str;
          }
        }
      });
      return pass;
    },

    // 品牌方信息
    getBrandDate() {
      getAllBrandsPage().then((res) => {
        this.brandList = res.data;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
}
</style>
